﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace Pixer
{
    class Line : Shape
    {
        private Point startPoint;

        public Point StartPoint
        {
            get { return startPoint; }
            set { startPoint = value; }
        }

        private Point endPoint;

        public Point EndPoint
        {
            get { return endPoint; }
            set { endPoint = value; }
        }

        #region Shape 成员

        public override void paint(System.Drawing.Graphics g)
        {
            g.DrawLine(Pens.Black, startPoint, endPoint);
        }

        /// <summary>
        /// 采用DDA画线算法画线
        /// </summary>
        /// <param name="b"></param>
        public override void paint(Bitmap b)
        {
            //int x, y, dx, dy, dk;
            //dx = endPoint.X - startPoint.X;
            //dy = endPoint.Y - startPoint.Y;
            //dk = 2 * dy - dx;
            //y = startPoint.Y;
            //for (x = startPoint.X; x <= endPoint.X; x++)
            //{
            //    try
            //    {
            //        b.SetPixel(x, y, lineColor);
            //    }
            //    catch (Exception ex)
            //    {
            //        break;
            //    }
            //    dk = dk + 2 * dy;
            //    if (dk >= 0)
            //    {
            //        y++;
            //        dk = dk - 2 * dx;
            //    }
            //}

            ////数值微分法
            //int x;
            //double k;
            //double y = startPoint.Y;
            //k = 1.0 * (endPoint.Y - startPoint.Y) / (endPoint.X - startPoint.X);
            //for (x = startPoint.X; x <= endPoint.X; x++)
            //{
            //    b.SetPixel(x,(int)(y+0.5),lineColor);
            //    y += k;
            //}


            float delta_x, delta_y, x, y;
            int dx, dy, steps, k;
            dx = endPoint.X - startPoint.X;
            dy = endPoint.Y - startPoint.Y;
            if (Math.Abs(dx) > Math.Abs(dy)) steps = Math.Abs(dx);
            else steps = Math.Abs(dy);
            delta_x = (float)dx / (float)steps;
            delta_y = (float)dy / (float)steps;
            x = startPoint.X;
            y = startPoint.Y;
            try
            {
                b.SetPixel((int)(x + 0.5), (int)(y + 0.5), lineColor);

                for (k = 1; k <= steps; k++)
                {
                    x += delta_x;
                    y += delta_y;

                    b.SetPixel((int)(x + 0.5), (int)(y + 0.5), lineColor);
                }
            }
            catch (Exception ex)
            {
            }

        }

        #endregion
    }
}
